package com.liuqi.openai.keyword;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * 精确匹配提取关键词, 提取最大长度的关键词
 *
 * @author liuqi
 * @date 2025/8/3
 **/
public class ExactMatchKeywordExtractor extends AbstractKeywordExtractor {

    public ExactMatchKeywordExtractor(List<Dictionary> dictionaries) {
        super(dictionaries);
    }

    public ExactMatchKeywordExtractor(List<Dictionary> dictionaries, Set<String> stopWords) {
        super(dictionaries, stopWords);
    }

    @Override
    protected MatchResult match(String text, int pos) {
        TrieNode current = root;
        int end = pos;
        int mark = end;

        // 检索次数
        int searchCount = 0;

        while (end < text.length()) {
            searchCount++;

            char ch = Character.toLowerCase(text.charAt(end));
            current = current.children.get(ch);
            if (current == null) {
                break;
            }
            end++;
            if (current.endOfWord) {
                // 标记一个已找到的关键词, 但不跳出循环, 继续寻找是否还有更长的关键词
                mark = end;
            }
        }

        if (mark != pos) {
            String result = text.substring(pos, mark);
            return new MatchResult(Arrays.asList(result), result.length(), searchCount);
        }

        return null;
    }
}
